package sd.zhr.moodcapsule.configure;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        response.setStatus(200);
        Map<String,Object> map = new HashMap<>();
        map.put("code",401);
        if(exception instanceof LockedException){
            map.put("msg","账户被锁定，登录失败！");
        }else if(exception instanceof BadCredentialsException){
            map.put("msg","账户名或密码输入错误，登录失败！");
        }else if(exception instanceof DisabledException){
            map.put("msg","账户被禁用，登录失败！");
        }else if(exception instanceof AccountExpiredException){
            map.put("msg","账户已过期，登录失败！");
        }else if(exception instanceof CredentialsExpiredException){
            map.put("msg","密码已过期，登录失败！");
        }else{
            map.put("msg","登录失败！");
        }
        ObjectMapper om = new ObjectMapper();
        out.write(om.writeValueAsString(map));
        out.flush();
        out.close();
    }
}
